﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
//using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using NET4.DataNET4.Repository;
using NET4.DataNET4;
using System.IO;
using System.Data.Linq;
using System.Drawing.Imaging;
using System.Text.RegularExpressions;

public partial class Image : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        byte[] image;
        int id;
        if (this.Request["id"] != null && int.TryParse(this.Request["id"], out id))
        {
            OfferteAanvraag aanvraag = OfferteAanvraagRepository.Instance.Select(id);
            if (aanvraag.Afbeelding != null)
            {
                image = aanvraag.Afbeelding.ToArray();
            }
            else
            {
                image = this.LoadNAImage();
            }
        }
        else
        {
            image = this.LoadNAImage();
        }
        Stream stream = new MemoryStream(image);
        StreamReader sr = new StreamReader(stream);
        char[] chrs = new char[20];
        sr.Read(chrs, 0, 20);
        string mimeType = new string(chrs);
        if (mimeType.MatchesPattern("JPG") || mimeType.MatchesPattern("JFIF") || mimeType.MatchesPattern("JPEG"))
        {
            this.Response.ContentType = "image/jpg";
        }
        else if(mimeType.MatchesPattern("PNG"))
        {
            this.Response.ContentType = "image/png";
        } 
        else if(mimeType.MatchesPattern("GIF"))
        {
            this.Response.ContentType = "image/gif";
        } 
        else
        {
            this.Response.ContentType = "image/jpg";
        }
        this.Response.BinaryWrite(image);
    }

    private byte[] LoadNAImage()
    {
        return Utils.ReadByteArrayFromFile(this.MapPath(@"Images\NA.png"));
    }
}
